using homework_2_test_first_development.Enums;
using homework_2_test_first_development.Models;
using homework_2_test_first_development.Validators;

namespace homework_2_test_first_development.Services;

public static class ReceiptPrinter
{
    public static string PrintReceipt(IEnumerable<string> selectedBarcodes, IEnumerable<Product> products)
    {
        string receiptContent = string.Empty;

        var validationResult = BarcodeValidator.ValidateBarcodes(selectedBarcodes, products);

        if (validationResult.Error != ErrorType.Valid)
        {
            receiptContent = CreateErrorReceipt(validationResult);
        }
        else
        {
            receiptContent = CreateValidReceipt(selectedBarcodes, products);
        }

        return receiptContent;
    }

    private static string CreateErrorReceipt(ValidationResult validationResult)
    {
        string[] header = { "ERROR", "-------" };

        string body = validationResult.Error switch
        {
            ErrorType.InvalidBarcode => "The barcode cannot be recognized",
            ErrorType.ProductNotFound => $"The product cannot be found: {validationResult.Barcode}",
            _ => throw new ArgumentOutOfRangeException(nameof(validationResult.Error),
              $"Not expected Error type: {validationResult.Error}"),
        };

        return string.Join(Environment.NewLine, header.Append(body));
    }

    private static string CreateValidReceipt(IEnumerable<string> selectedBarcodes, IEnumerable<Product> products)
    {
        var barcodesAndAmount = BarcodeProcessor.ParseBarcodes(selectedBarcodes);
        var groupedBarcodes = BarcodeProcessor.GroupBarcodes(barcodesAndAmount);
        var receipt = ReceiptCreator.CreateReceipt(groupedBarcodes, products);

        return ReceiptFormatter.FormatReceipt(receipt);
    }
}
